import * as echarts from '../../../../packages/ec-canvas/echarts';
import regeneratorUntime from '../../../../utils/runtime.js'
var util = require('../../../../utils/public');
let chartLine1;//血压
let chartLine2;//血糖，血脂
let chartLine3;//肌酐，尿蛋白

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    ecLine2:{
      type:Object,
      value:{
        onInit: function (canvas, width, height,dpr){
          //初始化echarts元素，绑定到全局变量，方便更改数据
          chartLine2 = echarts.init(canvas, null, {
              width: width,
              height: height,
              devicePixelRatio: dpr // new
          });
          canvas.setChart(chartLine2);

          //可以先不setOption，等数据加载好后赋值，
          //不过那样没setOption前，echats元素是一片空白，体验不好，所有我先set。
          var xData = [1,2,3]  // x轴数据 自己写
          var title = "肌酐，尿蛋白"
          var legend = ['肌酐','尿蛋白']
          var option = getOption(title,legend,xData);
          chartLine2.setOption(option);
      
        },
    
      } 
    }
    
  },

  /**
   * 组件的初始数据
   */
  data: {
    //swiper
    indicatorDots:true,
    autoplay: false,
    interval:2000,
    duration:500,
    background:['血压','血糖','尿蛋白','尿比重','尿pH','尿量','肌酐'],
    //图表
    index:0,
    title:'血压',//string
    legend:[],//['肌酐','尿蛋白']
    xData:[],//[1,2,3]
    data_cur:[],//
    data_his:[],//
    yname:'mmHg',//纵坐标
    //请求的数据
    pressure1:[],
    pressure2:[],
    sugar:[],
    fat:[],
    uricProtein:[],
    uricGravity:[],
    uricpH:[],
    uricVolume:[],
    creatinine:[],
    ///echart
    ecLine:{
      lazyLoad: true
    },
    //轮播图抖动
    changing:false,
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onSlideChangeEnd: function (e) {
      var that = this;
      var index = e.detail.current
      if(!that.data.changing){
        that.setData({
          changing:true
        })
      switch(index){
        case 0://血压
          that.__proto__.initBloodPressure(that)
          break;
        case 1://血糖血脂
          that.__proto__.initBloodSugar(that)
          break;
        case 2://尿蛋白
          that.__proto__.initUricProtein(that)
          break;
        case 3://尿比重
          that.__proto__.initUricGravity(that)
          break;
        case 4://尿pH
          that.__proto__.initUricpH(that)
          break;
        case 5://尿量
          that.__proto__.initUricVolume(that)
          break;
        case 6://肌酐
          that.__proto__.initCreatinine(that)
          break;
      }
      setTimeout(function () {
        that.setData({
          changing:false
        })
      }, 500)
    }
      // that.setData({
      //   index: e.detail.current + 1
      // })
      console.log(e.detail.current)
    },
    // test:function(){
    //   var that = this
    //   this.__proto__.initBloodPressure(that)
    // },
    initCreatinine:async function(that){
      var _cur = that.data.creatinine
      var _xData = getxAxisFromToday()
      that.setData({
        // index:0,
        // title:'',
        legend:['肌酐'],
        xData:_xData,
        data_cur:_cur,
        yname:'μmol/L'
      })
      // that.__proto__.init(that)
      setTimeout(function () {
        wx.hideLoading()
      }, 0)
      //init
      that.ecComponent = that.selectComponent('#mychart');
      that.ecComponent.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        getOption2(chart,that);
        return chart;
      });
    },
    initUricVolume:async function(that){
      var _cur = that.data.uricVolume
      var _xData = getxAxisFromToday()
      that.setData({
        // index:0,
        // title:'',
        legend:['尿量'],
        xData:_xData,
        data_cur:_cur,
        yname:'ml'
      })
      // that.__proto__.init(that)
      setTimeout(function () {
        wx.hideLoading()
      }, 0)
      //init
      that.ecComponent = that.selectComponent('#mychart');
      that.ecComponent.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        getOption2(chart,that);
        return chart;
      });
    },
    initUricpH:async function(that){
      var _cur = that.data.uricpH
      var _xData = getxAxisFromToday()
      that.setData({
        // index:0,
        // title:'',
        legend:['尿pH'],
        xData:_xData,
        data_cur:_cur,
        yname:''
      })
      // that.__proto__.init(that)
      setTimeout(function () {
        wx.hideLoading()
      }, 0)
      //init
      that.ecComponent = that.selectComponent('#mychart');
      that.ecComponent.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        getOption2(chart,that);
        return chart;
      });
    },
    initUricGravity:async function(that){
      var _cur = that.data.uricGravity
      var _xData = getxAxisFromToday()
      that.setData({
        // index:0,
        // title:'',
        legend:['尿比重'],
        xData:_xData,
        data_cur:_cur,
        yname:''
      })
      // that.__proto__.init(that)
      setTimeout(function () {
        wx.hideLoading()
      }, 0)
      //init
      that.ecComponent = that.selectComponent('#mychart');
      that.ecComponent.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        getOption2(chart,that);
        return chart;
      });
    },
    initUricProtein:async function(that){
      var _cur = that.data.uricProtein
      console.log(_cur)
      var _xData = getxAxisFromToday()
      that.setData({
        // index:0,
        // title:'',
        legend:['尿蛋白'],
        xData:_xData,
        data_cur:_cur,
        yname:'mg'
      })
      // that.__proto__.init(that)
      setTimeout(function () {
        wx.hideLoading()
      }, 0)
      //init
      that.ecComponent = that.selectComponent('#mychart');
      that.ecComponent.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        getOption2(chart,that);
        return chart;
      });
    },
    initBloodSugar:async function(that){
      var _cur = that.data.sugar
      console.log(_cur)
      // var _his = that.data.fat
      // console.log(_his)
      var _xData = getxAxisFromToday()
      that.setData({
        // index:0,
        // title:'',
        legend:['血糖'],
        xData:_xData,
        data_cur:_cur,
        // data_his:_his,
        yname:'mmol/L'
      })
      // that.__proto__.init(that)
      setTimeout(function () {
        wx.hideLoading()
      }, 0)
      //init
      that.ecComponent = that.selectComponent('#mychart');
      that.ecComponent.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        getOption2(chart,that);
        return chart;
      });
    },
    initBloodPressure:async function(that){
      var _cur = that.data.pressure1
      console.log(_cur)
      var _his = that.data.pressure2
      console.log(_his)
      var _xData = getxAxisFromToday()
      that.setData({
        // index:0,
        // title:'',
        legend:['收缩压','舒张压'],
        xData:_xData,
        data_cur:_cur,
        data_his:_his,
        yname:'mmHg'
      })
      // that.__proto__.init(that)
      setTimeout(function () {
        wx.hideLoading()
      }, 0)
      //init
      that.ecComponent = that.selectComponent('#mychart');
      that.ecComponent.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        getOption(chart,that);
        return chart;
      });
    },
    //TODO:用getOption替换setChart,并设置参数
    init: function (that) {
      that.ecComponent = that.selectComponent('#mychart');
      that.ecComponent.init((canvas, width, height, dpr) => {
        // 获取组件的 canvas、width、height 后的回调函数
        // 在这里初始化图表
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        getOption(chart,that);
  
        // 将图表实例绑定到 this 上，可以在其他成员函数（如 dispose）中访问
        this.chart = chart;
  
        // this.setData({
        //   isLoaded: true,
        //   isDisposed: false
        // });
  
        // 注意这里一定要返回 chart 实例，否则会影响事件处理等
        return chart;
      });
    },
  },
  lifetimes: {
    created:async function(){
      var that = this
      console.log(this)
      // wx.showLoading({
      //   title: '正在加载',
      //   mask:true
      // })
      await getRecords(that)
      that.__proto__.initBloodPressure(that)//初始化数值
      // this.ecComponent = this.selectComponent('#mychart');
      // console.log(this.ecComponent)
      // this.__proto__.init(that)
    },
    attached: function() {
      // 在组件实例进入页面节点树时执行
    },
  },


})
function getOption2(chart,that) {
  var option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    backgroundColor: "#fff",
    color: ['#37A2DA','#67E0e3','#9FE6B8'],
    legend: {
      data: that.data.legend,
      top: 10,
      left: 'center',
      // backgroundColor: 'red',
      z: 100
    },
    grid: {
      top:"25%",
      left: "10%",
      right: "10%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: 'category',
      // boundaryGap: false,
      data: that.data.xData.reverse()||[],
      axisLabel: {
        interval: 0,
        rotate: 20
      },
    },
    yAxis: {
      x: 'center',
      name: that.data.yname,
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: that.data.legend[0],
      // zIndex:3,
      type: 'line',
      symbolSize: 3,
      smooth:true,
      data: that.data.data_cur.reverse()||[],
      // data: that.data.data_cur,
      markPoint: {
        data: [
          { type: 'max', name: 'Max' },
          { type: 'min', name: 'Min' }
        ]
      },
      markLine: {
        data: [{ type: 'average', name: 'Avg' }]
      }
    },
  ]
  };
  chart.setOption(option);
}
function getOption(chart,that) {
  var option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    backgroundColor: "#fff",
    color: ['#37A2DA','#67E0e3','#9FE6B8'],
    legend: {
      data: that.data.legend,
      top: 10,
      left: 'center',
      // backgroundColor: 'red',
      z: 100
    },
    grid: {
      top:"25%",
      left: "10%",
      right: "10%",
      bottom: "3%",
      containLabel: true
    },
    xAxis: {
      type: 'category',
      // boundaryGap: false,
      data: that.data.xData.reverse()||[],
      axisLabel: {
        interval: 0,
        rotate: 20
    },
      // axisLabel: {
      //   interval: 11,
      //   formatter: function (value, index) {
      //     return value.substring(0, 2) * 1;
      //   },
      //   textStyle: {
      //     fontsize: '10px'
      //   }
      // }
    },
    yAxis: {
      x: 'center',
      name: that.data.yname,
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    // dataZoom: [
    //   {
    //     type:"slider",//slider表示有滑动块的，
    //     show:true,
    //     // xAxisIndex:[1],//表示x轴折叠
    //     // start:1,//数据窗口范围的起始百分比,表示1%
    //     // end:35//数据窗口范围的结束百分比,表示35%坐标
    //   }
    // ],
    series: [{
      name: that.data.legend[0],
      // zIndex:3,
      type: 'line',
      symbolSize: 3,
      smooth:true,
      data: that.data.data_cur.reverse()||[],
      // data: that.data.data_cur,
      markPoint: {
        data: [
          { type: 'max', name: 'Max' },
          { type: 'min', name: 'Min' }
        ]
      },
      markLine: {
        data: [{ type: 'average', name: 'Avg' }]
      }
    },{
        name: that.data.legend[1],
        // zIndex: 2,
        type: 'line',
        symbolSize: 3,
        smooth: true,
        data: that.data.data_his.reverse()||[],
        markPoint: {
          data: [
            { type: 'max', name: 'Max' },
            { type: 'min', name: 'Min' }
          ]
        },
        markLine: {
          data: [{ type: 'average', name: 'Avg' }]
        }
    }
  ]
  };
  chart.setOption(option);
}
function gettimeStamp(days){
  var timestamp = Date.parse(new Date());
  var before_timetamp = timestamp*0.001 - 24 * 60 * 60 * days;
  return before_timetamp
}
function getxAxisFromToday(){
  var xAxis=[]
  for(var i = 0;i < 7;i++){
    xAxis.push(util.getMyDateWithoutYear(gettimeStamp(i)))
  }
  return xAxis
}
async function getRecords(that){
  var that = that
  console.log(that)
  //血压
  var pressure1=[]
  var pressure2=[]
  //血糖，血脂
  var sugar=[]
  var fat=[]
  //尿蛋白，尿比重,尿ph,尿量
  var uricProtein=[]
  var uricGravity=[]
  var uricpH=[]
  var uricVolume=[]
  //肌酐
  var creatinine=[]
  for(var i = 0;i<7;i++){
    var year = new Date(gettimeStamp(i)*1000).getFullYear()
    var month = new Date(gettimeStamp(i)*1000).getMonth() + 1
    var day = new Date(gettimeStamp(i)*1000).getDate()
    var _date={year,month,day}
    var records = await getDakaRecords(that,_date)
    if(records==null){
      pressure1.push(null)
      pressure2.push(null)
      sugar.push(null)
      fat.push(null)
      uricProtein.push(null)
      uricGravity.push(null)
      uricpH.push(null)
      uricVolume.push(null)
      creatinine.push(null)
    }else{
      //pressure1
      if(records._bloodPressure1!=null&&records._bloodPressure1.length>0)
      pressure1.push(parseFloat(records._bloodPressure1))
      else
      pressure1.push(null)
      //pressure2
      if(records._bloodPressure2!=null&&records._bloodPressure2.length>0)
      pressure2.push(parseFloat(records._bloodPressure2))
      else
      pressure2.push(null)
      //sugar
      if(records._bloodSugar!=null&&records._bloodSugar.length>0)
      sugar.push(parseFloat(records._bloodSugar))
      else
      sugar.push(null)
      //fat
      if(records._bloodFat!=null&&records._bloodFat.length>0)
      fat.push(parseFloat(records._bloodFat))
      else
      fat.push(null)
      //_uricProtein
      if(records._uricProtein!=null&&records._uricProtein.length>0)
      uricProtein.push(parseFloat(records._uricProtein))
      else
      uricProtein.push(null)
      //_uricGravity
      if(records._uricGravity!=null&&records._uricGravity.length>0)
      uricGravity.push(parseFloat(records._uricGravity))
      else
      uricGravity.push(null)
      //_uricpH
      if(records._uricpH!=null&&records._uricpH.length>0)
      uricpH.push(parseFloat(records._uricpH))
      else
      uricpH.push(null)
      //_uricVolume
      if(records._uricVolume!=null&&records._uricVolume.length>0)
      uricVolume.push(parseFloat(records._uricVolume))
      else
      uricVolume.push(null)
      //_creatinine
      if(records._creatinine!=null&&records._creatinine.length>0)
      creatinine.push(parseFloat(records._creatinine))
      else
      creatinine.push(null)
    }
  }
  that.setData({
    pressure1:pressure1,
    pressure2:pressure2,
    sugar:sugar,
    fat:fat,
    uricProtein:uricProtein,
    uricGravity:uricGravity,
    uricpH:uricpH,
    uricVolume:uricVolume,
    creatinine:creatinine
  })
  console.log(that.data.pressure1)
  console.log(that.data.pressure2)
  console.log(that.data.sugar)
  console.log(that.data.fat)
  console.log(that.data.uricProtein)
  console.log(that.data.uricGravity)
  console.log(that.data.uricpH)
  console.log(that.data.uricVolume)
  console.log(that.data.creatinine)
  //获取全部records匹配同一天，找到其他数据
  // console.log(detailPage)
}
async function getBloodPressure(){
  var that = this
  var pressure=[]
  for(var i = 0;i<7;i++){
    var year = new Date(gettimeStamp(i)*1000).getFullYear()
    var month = new Date(gettimeStamp(i)*1000).getMonth() + 1
    var day = new Date(gettimeStamp(i)*1000).getDate()
    var _date={year,month,day}
    var records = await getDakaRecords(that,_date)
    if(records==null){
      pressure.push(null)
    }else{
      pressure.push(parseFloat(records._bloodPressure1))
    }
  }
  return pressure
  //获取全部records匹配同一天，找到其他数据
  // console.log(detailPage)
}
async function getBloodPressure2(){
  var that = this
  var pressure=[]
  for(var i = 0;i<7;i++){
    var year = new Date(gettimeStamp(i)*1000).getFullYear()
    var month = new Date(gettimeStamp(i)*1000).getMonth() + 1
    var day = new Date(gettimeStamp(i)*1000).getDate()
    var _date={year,month,day}
    var records = await getDakaRecords(that,_date)
    if(records==null){
      pressure.push(null)
    }else{
      pressure.push(parseFloat(records._bloodPressure2))
    }
  }
  console.log(pressure)
  return pressure
  //获取全部records匹配同一天，找到其他数据
  // console.log(detailPage)
}
function compareDay(_date,r){
  for(var i = 0;i<r.length;i++){
    if(_date.year==r[i].year &&
      _date.month==r[i].month &&
      _date.day==r[i].date){
        return i
      }
  }
  return null
}
 async function getDakaRecords(that,_date){
   var records = null
   try{
  var res = await wx.cloud.callFunction({
    name:'clockIn',
    data:{
      type:"getRecords",
      openid:wx.getStorageSync('openid')
    }
  });
  var tempRecords = res.result.records
      //获取日期数组，匹配index获取其他数据
      const r = tempRecords.map(item=>{
        var tempDate =new Date(item._date);
        return {
          year: tempDate.getFullYear(),
          month:tempDate.getMonth()+1,
          date:tempDate.getDate()
        }
      })
      var index = compareDay(_date,r)
      records = tempRecords[index]
}catch(error){
  return null;
  } 
  return records
  
}
async function determinValue1(){
  var pressure1_cur = await getBloodPressure()
  return {
    onInit: function (canvas, width, height,dpr){
      console.log()
      //初始化echarts元素，绑定到全局变量，方便更改数据
      chartLine1 = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
      });
      canvas.setChart(chartLine1);

      //可以先不setOption，等数据加载好后赋值，
      //不过那样没setOption前，echats元素是一片空白，体验不好，所有我先set。
      var xData = getxAxisFromToday()  // x轴数据 自己写
      // var xData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      var title = "血压"
      var legend = ['舒张压','收缩压']  
      var data_cur = _cur
      var option = getOption(title,legend,xData,data_cur);
      chartLine1.setOption(option);
  },
  }
}

// function setOption(chart) {
//   const option = {
//     tooltip: {
//       trigger: 'axis',
//       axisPointer: {            // 坐标轴指示器，坐标轴触发有效
//         type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
//       }
//     },
//     legend: {
//       data: ['热度', '正面', '负面']
//     },
//     grid: {
//       left: 20,
//       right: 20,
//       bottom: 15,
//       top: 40,
//       containLabel: true
//     },
//     xAxis: [
//       {
//         type: 'value',
//         axisLine: {
//           lineStyle: {
//             color: '#999'
//           }
//         },
//         axisLabel: {
//           color: '#666'
//         }
//       }
//     ],
//     yAxis: [
//       {
//         type: 'category',
//         axisTick: { show: false },
//         data: ['汽车之家', '今日头条', '百度贴吧', '一点资讯', '微信', '微博', '知乎'],
//         axisLine: {
//           lineStyle: {
//             color: '#999'
//           }
//         },
//         axisLabel: {
//           color: '#666'
//         }
//       }
//     ],
//     series: [
//       {
//         name: '热度',
//         type: 'bar',
//         label: {
//           normal: {
//             show: true,
//             position: 'inside'
//           }
//         },
//         data: [300, 270, 340, 344, 300, 320, 310],
//         itemStyle: {
//           // emphasis: {
//           //   color: '#37a2da'
//           // }
//         }
//       },
//       {
//         name: '正面',
//         type: 'bar',
//         stack: '总量',
//         label: {
//           normal: {
//             show: true
//           }
//         },
//         data: [120, 102, 141, 174, 190, 250, 220],
//         itemStyle: {
//           // emphasis: {
//           //   color: '#32c5e9'
//           // }
//         }
//       },
//       {
//         name: '负面',
//         type: 'bar',
//         stack: '总量',
//         label: {
//           normal: {
//             show: true,
//             position: 'left'
//           }
//         },
//         data: [-20, -32, -21, -34, -90, -130, -110],
//         itemStyle: {
//           // emphasis: {
//           //   color: '#67e0e3'
//           // }
//         }
//       }
//     ]
//   };
//   chart.setOption(option);
// }
